package cn.itsub.boot.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils {

    private static org.springframework.context.ApplicationContext context;

    @Autowired
    private void setContext(org.springframework.context.ApplicationContext context){
        SpringUtils.context = context;
    }

    public static <T> T getBean(Class<T> clazz){
        return context.getBean(clazz);
    }

    public static ApplicationContext getContext(){
        return context;
    }

    public static void printWebUrl(){
        String port = context.getEnvironment().getProperty("server.port");
        String contextPath = context.getEnvironment().getProperty("server.servlet.context-path");
        String protocol = "http";
        String host = "localhost";
        String ctx = contextPath == null ? "/" : contextPath;
        System.out.printf("Application is running at %s://%s:%s%s%n", protocol, host, port, ctx);
    }

}
